package com.store.satring.config;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
import org.springframework.security.crypto.codec.Base64;

//import org.springframework.security.core.authority.AuthorityUtils;
//import org.springframework.security.core.userdetails.User;
//import org.springframework.security.core.userdetails.UserDetails;
//import org.springframework.security.core.userdetails.UsernameNotFoundException;
//import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
import com.store.satring.dos.aa.Users;

public class CustomJdbcDAOImpl extends JdbcDaoImpl {

	public static final String usersByUsernameQuery = "select login_id, password, disabled "
			+ "from users " + "where login_id = ?";

	protected List<UserDetails> loadUsersByUsername(String loginId) {

		List<UserDetails> list = new ArrayList<UserDetails>();

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {

			conn = getDataSource().getConnection();
			ps = conn.prepareStatement(usersByUsernameQuery);
			ps.setString(1, loginId);
			rs = ps.executeQuery();
			String pass = null;
			boolean disabled = true;
			if (rs.next()) {
				loginId = rs.getString("login_Id");
				pass = rs.getString("password");
				int inActive = rs.getInt("disabled");
				disabled = inActive == 1 ? true : false;
				pass = new String(Base64.decode(pass.getBytes()));

				Users user = Users.findUser(loginId);
				if (user != null) {
					if (user.getDisabled()) {
						disabled = true;
					} else {
						disabled = false;
					}
				} else {
					return list;
				}

			}
			list.add(new User(loginId, pass, !disabled, true, true, true,
					AuthorityUtils.NO_AUTHORITIES));

		} catch (SQLException e) {
			String msg = "Exception occured while Authentication, Message : "
					+ (e != null ? e.getMessage() : "");
			throw new UsernameNotFoundException(msg);
		} finally {
			close(rs, null, ps, conn);
		}

		return list;
	}

	public void close(ResultSet rs, Statement stmt, PreparedStatement pstmt,
			Connection conn) {

		try {
			if (rs != null) {
				rs.close();
			}

			if (stmt != null) {
				stmt.close();
			}
			if (pstmt != null) {
				pstmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

}
